package day05;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

import java.math.BigInteger;
import java.util.Scanner;

/**
 * @author yangwenqi
 * @decs TODO
 * @date 2025/4/24
 */
public class BigIntegerDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个十六进制数：");
        String num = sc.nextLine().trim();
        System.out.println(num + " 的十进制值是：" + HexToDecimal(num));
    }

    public static BigInteger HexToDecimal(String num) {
        if (num.startsWith("0x") || num.startsWith("0X")) {
            num = num.substring(2);
        }
        char[] c = num.toCharArray();
        BigInteger decimal = BigInteger.ZERO;
        BigInteger base = BigInteger.valueOf(16);
        for (int i = 0; i < c.length; i++) {
            int value=0;
            if (c[i] >= '0' && c[i] <= '9') {
                value = c[i];
            } else if (c[i] >= 'a' && c[i] <= 'f') {
                value = c[i] - 'a' + 10;
            } else if (c[i] >= 'A' && c[i] <= 'F') {
                value = c[i] - 'A' + 10;
            }
            BigInteger currentValue = BigInteger.valueOf(value)
                    .multiply(base.pow(c.length - 1 - i));
            decimal = decimal.add(currentValue);
        }
        return decimal;
    }
}
